import re

from django.contrib.auth.backends import ModelBackend
# from django.contrib.auth.models import User
from users.models import User


def get_user_by_account(username):
    try:
        if re.match('^1[345789]\d{9}$', username):
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)
    except Exception:
        return None
    else:
        return user


class UsernameMobileLogin(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
         user = get_user_by_account(username)

         if user and user.check_password(password):
             return user


